#!/bin/bash

JAVAC=javac
JAVA=java
DIRECTORY=$(cd `dirname .` && pwd)

CLASSPATH=$DIRECTORY/tools/

CUP="$JAVA -cp $CLASSPATH java_cup.Main"

JFLEX="$JAVA -cp $CLASSPATH JFlex.Main"

echo ' --- Creazione della cartella sorgenti'
rm -fR gensrc >& /dev/null
mkdir gensrc >& /dev/null

echo ' --- Creazione della cartella dei log "build"'
rm -fR build >& /dev/null
mkdir build >& /dev/null

echo ' --- Creazione della cartella bin"'
rm -fR bin >& /dev/null
mkdir bin >& /dev/null

echo ' --- Copio i file da src a gensrc'
cp -R src/* gensrc/
cd gensrc

echo ' --- Genero il parser (parser.cup)'
$CUP parser.cup >& ../build/cup.txt
mv parser.java glemipsc/
mv sym.java glemipsc/
cd ..

echo ' --- Genero gli scanner (*.jflex)'
JFLEX_PREPARSER=`find 'gensrc/' -name 'pre-parser.lex'`
JFLEX_SCANNER=`find 'gensrc/' -name 'scanner.lex'`
$JFLEX --skel 'gensrc/skeleton.nested' $JFLEX_PREPARSER >& build/pre-parser.txt
$JFLEX  $JFLEX_SCANNER>& build/scanner.txt
mv gensrc/PreParser.java gensrc/glemipsc/
mv gensrc/Lexer.java gensrc/glemipsc/

echo ' --- Compilo i sorgenti Java generati'
SOURCES=`find 'gensrc/' -name '*.java'`
rm -Rf *~ src/*~ bin/* >& /dev/null
$JAVAC -cp ./bin/:./gensrc/:$CLASSPATH -d bin $SOURCES >& build/javac.txt

echo ' --- Creazione del file JAR nella cartella test'
if [ -f GLEMipsC.jar ]; then rm GLEMipsC.jar; fi
cd bin
mkdir ./java_cup
cp -rf ../tools/java_cup/runtime/ ./java_cup/runtime
jar cfm ../GLEMipsC.jar ../MANIFEST.MF glemipsc/ java_cup/runtime
cd ..
rm -fR gensrc >& /dev/null
rm -fR bin >& /dev/null
echo ' --- Il processo è terminato. Ora è possibile leggere i log presenti nella cartella "build"'
